const frame = document.querySelector('div.popout');

function fadeIn(){
    frame.style.display = 'block';
    setTimeout(() => {
        frame.style.opacity = 1;
    }, 20);
}

function fadeOut(){
    frame.style.opacity = 0;
    setTimeout(() => {
        frame.style.display = 'none';
    }, 300);
}

function lyd_close(){
    frame.removeChild(document.querySelector('div.dialog'));
    setTimeout(() => {
        fadeOut();
    }, 20);
}

// Dialog 1
function lyd1_true(type, c_w_id){
    const callPath = {
        0: '/counter/rmCounter', 
        1: '/waypoint/rmWaypoint'
    }
    const callArgs = {
        0: `counterCid=${c_w_id}&updateUserID=${localStorage.getItem('ID')}`,
        1: `waypointCid=${c_w_id}&updateUserID=${localStorage.getItem('ID')}`
    }
    callServer(callPath[type], callArgs[type], null, 'DELETE')
        .then(response => {
            if (response[0] == 'OK'){
                if(type == 0){
                    initCounterInterface();
                    initSettingInterface();
                }
                if(type == 1){
                    initWaypointInterface();
                }
                lyd_close();
            }
        })
        .catch(ex => {
            console.error(`Request(Type 1) Failed: ${ex}`);
        })
}

function lyDialogType1(type, title, info, c_w_id){
    const div = document.createElement("div");
    div.classList.add("dialog");
    div.id = "lyDialogType1";
    //
    const h1 = document.createElement("h1");
    h1.classList.add("dTitle");
    h1.textContent = "Confirm？";
    //
    const span1 = document.createElement("span");
    span1.textContent = "Are you sure want to delete the ";
    //
    const span2 = document.createElement("span");
    const tcList = {
        0: `"${title}"（With ${info.replace('（', '').replace('）', '').replace(/by/g, '，last update by')}）？`,
        1: `"${title}"（Add by ${info}）？`
    }
    span2.textContent = tcList[type];
    //
    const br1 = document.createElement("br");
    //
    const br2 = document.createElement("br");
    //
    const span3 = document.createElement("span");
    span3.textContent = "⚠ NB! No way to Undo this delete ⚠";
    span3.style.color = "red";
    //
    const divBtns = document.createElement("div");
    divBtns.classList.add("btns");
    //
    const button1 = document.createElement("button");
    button1.classList.add("true");
    button1.textContent = "Yes";
    button1.onclick = function(){
        lyd1_true(type, c_w_id)
    }
    //
    const button2 = document.createElement("button");
    button2.classList.add("false");
    button2.textContent = "Cancel";
    button2.setAttribute("onclick", "lyd_close()");
    //
    divBtns.appendChild(button1);
    divBtns.appendChild(button2);
    //
    div.appendChild(h1);
    div.appendChild(span1);
    div.appendChild(br1);
    div.appendChild(span2);
    div.appendChild(br2);
    div.appendChild(span3);
    div.appendChild(divBtns);
    //
    frame.appendChild(div);
    fadeIn();
}

// Dialog 2
function lyd2_true(name){
    callServer('/counter/addCounter',`counterName=${name}&updateUserID=${localStorage.getItem('ID')}`, null, 'POST')
        .then(response => {
            if (response[0] == 'OK'){
                initSettingInterface();
                initCounterInterface();
                lyd_close();
            }
        })
        .catch(ex => {
            console.error(`Request(Type 2) Failed: ${ex}`);
        })
}

function lyDialogType2(){
    const div = document.createElement('div');
    div.classList.add('dialog');
    div.id = 'lyDialogType2';
    //
    const h1 = document.createElement('h1');
    h1.classList.add('dTitle');
    h1.textContent = 'Unit Name？';
    //
    const input = document.createElement('input');
    input.type = 'text';
    input.id = 'unitName';
    input.placeholder = 'Enter the name of unit，must able for JSON value';
    input.addEventListener('input', function (){
        const createButton = document.querySelector('#lyDialogType2 .btns button.true');
        if (this.value.trim() !== '') {
            createButton.disabled = false;
        } else {
            createButton.disabled = true;
        }
    });
    //
    const btnDiv = document.createElement('div');
    btnDiv.classList.add('btns');
    //
    const createButton = document.createElement('button');
    createButton.type = 'button';
    createButton.classList.add('true');
    createButton.disabled = true;
    createButton.textContent = 'Create';
    createButton.onclick = function() {
        lyd2_true(input.value.trim());
    };
    //
    const cancelButton = document.createElement('button');
    cancelButton.type = 'button';
    cancelButton.classList.add('false');
    cancelButton.textContent = 'Cancel';
    cancelButton.addEventListener('click', lyd_close);
    //
    btnDiv.appendChild(createButton);
    btnDiv.appendChild(cancelButton);
    //
    div.appendChild(h1);
    div.appendChild(input);
    div.appendChild(btnDiv);
    //
    frame.appendChild(div);
    fadeIn();
}

// Dialog 3
function lyd3_true(name, x, y, z, dim){
    callServer('/waypoint/addWaypoint',`waypointName=${name}&X=${x}&Y=${y}&Z=${z}&Dim=${dim}&updateUserID=${localStorage.getItem('ID')}`, null, 'POST')
        .then(response => {
            if (response[0] == 'OK'){
                initWaypointInterface()
                lyd_close()
            }
        })
        .catch(ex => {
            console.error(`Request(Type 3) Failed: ${ex}`)
        })
}

function lyDialogType3(){
    const div = document.createElement('div');
    div.className = 'dialog';
    div.id = 'lyDialogType3';
    //
    const h1 = document.createElement('h1');
    h1.className = 'dTitle';
    h1.textContent = 'Waypoint Config？';
    //
    const input1 = document.createElement('input');
    input1.type = 'text';
    input1.id = 'waypointName';
    input1.placeholder = 'Enter the name of waypoint，must able for JSON value';
    input1.addEventListener('input', function (){
        const createButton = document.querySelector('#lyDialogType3 .btns button.true');
        if (input1.value.trim() !== '' && input2.value.trim() !== '' && input3.value.trim() !== '' && input4.value.trim() !== '' && getSelector() != '') {
            createButton.disabled = false;
        } else {
            createButton.disabled = true;
        }
    });
    //
    const input2 = document.createElement('input');
    input2.type = 'text';
    input2.id = 'X';
    input2.placeholder = 'Enter the x-coordinate of unit，must is a number';
    input2.addEventListener('input', function (){
        const createButton = document.querySelector('#lyDialogType3 .btns button.true');
        if (input1.value.trim() !== '' && input2.value.trim() !== '' && input3.value.trim() !== '' && input4.value.trim() !== '' && getSelector() != '') {
            createButton.disabled = false;
        } else {
            createButton.disabled = true;
        }
    });
    //
    const input3 = document.createElement('input');
    input3.type = 'text';
    input3.id = 'Y';
    input3.placeholder = 'Enter the y-coordinate of unit，must is a number';
    input3.addEventListener('input', function (){
        const createButton = document.querySelector('#lyDialogType3 .btns button.true');
        if (input1.value.trim() !== '' && input2.value.trim() !== '' && input3.value.trim() !== '' && input4.value.trim() !== '' && getSelector() != '') {
            createButton.disabled = false;
        } else {
            createButton.disabled = true;
        }
    });
    //
    const input4 = document.createElement('input');
    input4.type = 'text';
    input4.id = 'Z';
    input4.placeholder = 'Enter the z-coordinate of unit，must is a number';
    input4.addEventListener('input', function (){
        const createButton = document.querySelector('#lyDialogType3 .btns button.true');
        if (input1.value.trim() !== '' && input2.value.trim() !== '' && input3.value.trim() !== '' && input4.value.trim() !== '' && getSelector() != '') {
            createButton.disabled = false;
        } else {
            createButton.disabled = true;
        }
    });
    //
    const select = document.createElement("select");
    select.id = "dim";
    select.name = "dim";
    select.addEventListener('change', function (){
        const createButton = document.querySelector('#lyDialogType3 .btns button.true');
        if (input1.value.trim() !== '' && input2.value.trim() !== '' && input3.value.trim() !== '' && input4.value.trim() !== '' && getSelector() != '') {
            createButton.disabled = false;
        } else {
            createButton.disabled = true;
        }
    })
    //
    const option1 = document.createElement("option");
    option1.value = "";
    option1.disabled = true;
    option1.selected = true;
    option1.textContent = "请选择";
    //
    const option2 = document.createElement("option");
    option2.value = "Overworld";
    option2.textContent = "Overworld";
    //
    const option3 = document.createElement("option");
    option3.value = "Nether";
    option3.textContent = "Nether";
    //
    const option4 = document.createElement("option");
    option4.value = "The End";
    option4.textContent = "The End";
    //
    select.appendChild(option1);
    select.appendChild(option2);
    select.appendChild(option3);
    select.appendChild(option4);
    //
    //
    const button1 = document.createElement('button');
    button1.type = 'button';
    button1.className = 'true';
    button1.disabled = true;
    button1.textContent = 'Create';
    button1.onclick = function(){
        lyd3_true(
            input1.value.trim(),
            input2.value.trim(),
            input3.value.trim(),
            input4.value.trim(),
            getSelector()
        );
    }
    //
    const button2 = document.createElement('button');
    button2.type = 'button';
    button2.className = 'false';
    button2.textContent = 'Cancel';
    button2.onclick = function(){
        lyd_close();
    }
    //
    const btnDiv = document.createElement('div');
    btnDiv.className = 'btns';
    //
    btnDiv.appendChild(button1);
    btnDiv.appendChild(button2);
    //
    div.appendChild(h1);
    div.appendChild(input1);
    div.appendChild(select);
    div.appendChild(input2);
    div.appendChild(input3);
    div.appendChild(input4);
    div.appendChild(btnDiv);
    //
    frame.appendChild(div)
    fadeIn()
}

function getSelector(){
    const select = document.getElementById("dim");
    const index = select.selectedIndex;
    const option = select.options[index];
    const value = option.value;
    return value
}

// Dialog 4
function lyDialogType4(statusCode){
    const messageDict = {
        400: 'It means you try to get datas but parameters are not fully provided<br>You may ask administrator for more information',
        403: 'It means you has no permission to get datas.<br>You need to enter your name at input (display a "here") in HomePage',
        500: 'It means server has some problems.<br>You may ask administrator for more information',
        503: 'It means service is not available.<br>You may ask administrator for more information',
        504: 'It means server has some problems.<br>You may ask administrator for more information',
    }
    if(statusCode in messageDict){
        var message = messageDict[statusCode]
    } else {
        var message = 'Unknown error!'
    }
    const dialogElement = document.createElement('div');
    dialogElement.classList.add('dialog');
    dialogElement.id = 'lyDialogType4';
    //
    const titleElement = document.createElement('h1');
    titleElement.classList.add('dTitle');
    titleElement.style.color = 'red';
    titleElement.innerHTML = 'Error!';
    dialogElement.appendChild(titleElement);
    //
    const statusElement = document.createElement('span');
    statusElement.innerHTML = 'Request Fail with status: ' + statusCode;
    dialogElement.appendChild(statusElement);
    //
    const br = document.createElement('br')
    dialogElement.appendChild(br);
    //
    const messageElement = document.createElement('span');
    messageElement.innerHTML = message;
    dialogElement.appendChild(messageElement);
    //
    const btnsElement = document.createElement('div');
    btnsElement.classList.add('btns');
    //
    const buttonElement = document.createElement('button');
    buttonElement.classList.add('false');
    buttonElement.innerHTML = 'Got it';
    buttonElement.onclick = lyd_close;
    //
    btnsElement.appendChild(buttonElement);
    dialogElement.appendChild(btnsElement);
    //
    frame.appendChild(dialogElement)
    fadeIn()
    message = null
}

setInterval(() => {
    if(document.querySelector('div.popout').style.display == 'none'){
        try{
            document.querySelector('div.popout').removeChild(document.querySelector('div.dialog'));
        } catch {}
    }
}, 1000)